import { observer } from 'mobx-react-lite'
import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import { storeAll } from '@/store'

const Users: React.FC = () => {
	const chartRef = useRef<HTMLDivElement>(null)
	const { usersStore: { users } } = storeAll

	useEffect(() => {
		if (!chartRef.current) return
		const data = []
		data.push(users.filter(item => item.age >= 18 && item.age < 25).length)
		data.push(users.filter(item => item.age >= 25 && item.age < 35).length)
		data.push(users.filter(item => item.age >= 35 && item.age < 45).length)
		data.push(users.filter(item => item.age >= 45 && item.age < 55).length)
		data.push(users.filter(item => item.age >= 55 && item.age < 60).length)
		const options: echarts.EChartOption = {
			// 标题
			title: {
				text: "用户年龄区间统计"
			},
			// 提示框组件
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				}
			},
			// 图例组件
			legend: {
			},
			// x轴
			xAxis: {
				name: '年龄区间',
				type: 'category',
				data: ['18~25', '26~35', '36~45', '46~55', '56~60']
			},
			// y轴
			yAxis: {
				name: '人数',
				type: 'value',
				minInterval: 1,
				// max: 10
			},
			series: [{
				data,
				// type: 'line' 折线图
				type: 'bar', // 柱状图
			}]
		}
		// 创建一个echarts实例，返回echarts实例。不能在单个容器中创建多个echarts实例
		const chart = echarts.init(chartRef.current)

		// 设置图表实例的配置项和数据
		chart.setOption(options)

		// 组件卸载
		return () => {
			// myChart.dispose() 销毁实例。实例销毁后无法再被使用
			chart.dispose()
		}
	}, [users])
	return <div ref={chartRef} style={{ width: "620px", height: "400px" }}></div>
}

export default observer(Users)